package com.yhj.servlet.container;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintWriter;

public class HttpServletResponse implements ServletResponse{
	
	private String webroot=System.getProperty("user.dir")+File.separator+"webapps";
	
	private ServletRequest request;
	/**一个响应头的示例
	 * HTTP/1.1 200 OK  
		Server: IBM/4.0  
		Date: Sat, 6 Nov 2013 13:13:00 GMT  
		Content-Type: text/html  
		Last-Modified: Sat, 5 Jan 2013 13:13:12 GMT  
		Content-Length: 112  
	 */
	private OutputStream out;
	
	/**
	 * 构造方法
	 * @param request
	 * @param out
	 */
	public HttpServletResponse(ServletRequest request,OutputStream out) {
		super();
		this.request=request;
		this.out = out;
	}
	
	public void sendRedirect(){
		/**
		 * 1.从request中取出uri
		 * 2.判断是否在本地存在uri指代的文件
		 * 3.没有404，有
		 * 4.以输入流读取这个文件
		 * 5.以输出流将文件写到客户端，要加入响应的协助
		 */
		String uri=request.getUri();
		if(uri==null){
			return;
		}
		File f=new File(webroot,uri);
		String responseprotocal=null;
		if(!f.exists()){
			//文件不存在，返回404
			String httpBody=readFile(new File(webroot,"404.html"));
			responseprotocal=gen404(httpBody.getBytes().length);
			responseprotocal+=httpBody;
		}else{
			String httpBody=readFile(f);
			responseprotocal=gen200(httpBody.getBytes().length);
			responseprotocal+=httpBody;
		}
		try{
			out.write(responseprotocal.getBytes());
			out.flush();
		}catch(Exception e){
			//输出500的错误
		}
		
	}

	private String gen200(int length) {
		String protocal200="HTTP/1.1 200 OK\r\nContent-Type: text/html\r\nContent-Length: "+length+"\r\n\r\n";
		return protocal200;
	}

	private String gen404(int length) {
		String protocal404="HTTP/1.1 404 File Not Found\r\nContent-Type: text/html\r\nContent-Length: "+length+"\r\n\r\n";
		return protocal404;
	}

	private String readFile(File f) {
		FileInputStream fis=null;
		StringBuffer sb=new StringBuffer();
		try {
			fis=new FileInputStream(f);
			byte[] bs=new byte[1024];
			int length=-1;
			while(	(length=fis.read(bs,0,bs.length))!=-1	){
				sb.append(new String(bs,0,length));
			}
		} catch (Exception e) {
			e.printStackTrace();
		}finally{
			if(fis!=null){
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		return sb.toString();
	}
	
	private PrintWriter output;

	@Override
	public PrintWriter getWriter() {
		this.output=new PrintWriter(out);
		return this.output;
	}
	
}
